#include <func.h>

int main()
{
    int semArrid = semget(1000, 1, IPC_CREAT | 0600);
    ERROR_CHECK(semArrid, -1, "semget");
    int ret = semctl(semArrid, 0, SETVAL, 1);
    ERROR_CHECK(ret, -1, "semctl");

    int shmid = shmget(1001, 4096, IPC_CREAT | 0600);
    ERROR_CHECK(shmid, -1, "shmget");
    int *p = (int *)shmat(shmid, NULL, 0);
    ERROR_CHECK(p, (void *)-1, "shmat");
    p[0] = 10;
    p[1] = 0;
    struct sembuf P;
    P.sem_num = 0;
    P.sem_flg = SEM_UNDO;
    P.sem_op = -1;

    struct sembuf V;
    V.sem_num = 0;
    V.sem_flg = SEM_UNDO;
    V.sem_op = 1;

    if (!fork())
    {
        while (1)
        {

            semop(semArrid, &P, 1);
            if (p[0] > 0)
            {
                printf("I am consumer,before consume,product=%d,space= %d\n",
                       p[0], p[1]);
                --p[0];
                printf("Buy a product\n");
                ++p[1];
                printf("I am consumer,after consume,product=%d,space= %d\n",
                       p[0], p[1]);
            }
            semop(semArrid, &V, 1);

            sleep(1);
        }
        exit(0);
    }
    else
    {

        while (1)

        {

            semop(semArrid, &P, 1);
            if (p[1] > 0)
            {
                printf("I am producer,before produce,product=%d,space= %d\n", p[0], p[1]);
                --p[1];
                printf("Produce a product\n");
                ++p[0];
                printf("I am producer,after produce,product=%d,space= %d\n",
                       p[0], p[1]);
                sleep(2);
            }
            semop(semArrid, &V, 1);
        }
        wait(NULL);
    }
    shmdt(p);
    shmctl(shmid, IPC_RMID, NULL);
    return 0;
}